<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './permission.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { createPermission, modifyPermission } from '/@/api/system/system';
  import { RoleReq } from '/@/api/system/modal/roleModel';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'PermissionDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const id = ref('');

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;

        if (unref(isUpdate)) {
          await setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增权限' : '编辑权限'));

      const { createMessage } = useMessage();

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          const roleReq: RoleReq = {
            ...values,
          };
          if (unref(isUpdate)) {
            roleReq.id = unref(id);
            await modifyPermission(roleReq);
          } else {
            await createPermission(roleReq);
          }
          closeDrawer();
          emit('success');
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          createMessage.error(msg);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
